<template>
  <div class="container">
    <PropTable
      :columns="column"
      :data="list"
      :total="total"
      @reset="reset"
      @onSubmit="onSubmit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @exportExcelAction="exportExcelAction"
      permissionPrefix="system:plan"
    >
      <!-- 业主单位 所在地区 行业 -->
      <template #otherSearch>
        <el-form-item label="所在地区" style="margin: 0px 0px 0px 0px">
          <el-cascader
            v-model="addressList"
            ref="ref_areaCodes"
            :options="areaCodelist"
            :props="areaCodeprops"
            clearable
          ></el-cascader>
        </el-form-item>

        <el-form-item label="业主单位" style="margin: 0px 0px 0px 0px">
          <el-input
            class="input-item"
            v-model="enterpriseName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>

        <!-- 行业 -->
        <el-form-item label="行业" style="margin: 0px 0px 0px 0px">
          <el-select
            v-model="industry"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请输入"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 创建时间 -->
        <el-form-item label="创建时间" style="margin: 3px 15px 3px 0px">
          <el-date-picker
            v-model="creatTime"
            type="daterange"
            range-separator="至"
            start-placeholder="请选择"
            end-placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="项目总投资额" style="margin: 3px 15px 3px 0px">
          <el-input
            clearable
            v-model="val.createInvestment"
            type="number"
            placeholder="最小值"
            @input="handleInput('min')"
            @blur="handleVal"
          >
          </el-input>
          <div class="center" style="margin-left: 5px; margin-right: 5px">
            <span>至</span>
          </div>
          <el-input
            clearable
            v-model="val.endInvestment"
            placeholder="最大值"
            type="number"
            @input="handleInput('max')"
            @blur="handleVal"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="合同工期" style="margin: 3px 15px 3px 0px">
          <el-date-picker
            v-model="datetime"
            type="daterange"
            range-separator="至"
            start-placeholder="请选择"
            end-placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </template>
      <!-- 计划状态 -->
      <template v-slot:planStatus="scope">
        <div v-if="!useEmpty(scope.row.planStatus)">
          {{ getStatusLabel(scope.row.planStatus) }}
        </div>
      </template>
      <!-- <el-icon><plus /></el-icon> -->

      <template #btn>
        <div style="display: flex; justify-content: flex-end">
          <el-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['system:plan:add']"
            v-if="userStore.rolescode!=15">新建项目信息</el-button>
        </div>
      </template>
      <template v-slot:operation="scope">
        <div style="display: flex; justify-content: flex-end">
          <!--只有审批通过才会显示按钮  -->
          <el-button
            v-if="(scope.row.planStatus === '1' && scope.row.showStatus === '1') && userStore.rolescode!=15"
            link
            type="primary"
            icon="Message"
            @click="approval(scope.row)"
          >
            转立项</el-button
          >
          <!--只有审批驳回才会显示编辑按钮  -->
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handeleEdit(scope.row)"
            v-if="(scope.row.planStatus === '0' || scope.row.planStatus === '3') && userStore.rolescode!=15">
            编辑
          </el-button>
          <el-button
            link
            type="success"
            icon="Delete"
            @click="handelDelete(scope.row)"
            v-if="userStore.userId === 1 && userStore.rolescode!=15">
            删除
          </el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handeleRevoke(scope.row)"
            v-if="scope.row.planStatus === '2' && userStore.rolescode!=15 ">
            撤回
          </el-button>

          <el-button
            v-if="scope.row.planStatus !== '0' || userStore.rolescode==15"
            link
            type="primary"
            icon="Edit"
            @click="handleDetails(scope.row)">
            详情
          </el-button>
        </div>
      </template>
    </PropTable>
  </div>
</template>
<script setup >
import { ref, reactive, onMounted, nextTick } from "vue";
//@ts-ignore
import PropTable from "@/components/Table/PropTable/index.vue";
//@ts-ignore
import { exportExcel } from "@/utils/exprotExcel";
import { ElMessageBox, ElMessage } from "element-plus";

import { useRouter, useRoute } from "vue-router";

import {
  conversionList,
  businessTypeList,
  deleconversion,
  location,
  industryApi,
  withdrawApi,
} from "@/api/project/conversion";

import { useEmpty, formatDate } from "@/utils/index";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const loading = ref(true);

const route = useRoute();
const router = useRouter();

const industry = ref("");
// const industrys = ref(""); //行业2
//  const industry=ref("")

// const createInvestment = ref();
// const endInvestment=ref();
const val = reactive({
  createInvestment: "",
  endInvestment: "",
  //  industry: "", //行业
});
const areaCodelist = ref([]);
const datetime = ref();
const creatTime = ref();
const projectCreatesTime = ref();
const projectEndTime = ref();

const areaCodeprops = {
  value: "id",
  label: "name",
  // checkStrictly: true,
  children: "rcDistrictList",
};

const addressList = ref([]);
const enterpriseName = ref("");

// const form = reactive({
//   enterpriseName: "", //业主单位
// });

const handelLocation = async () => {
  try {
    let params = {};
    const response = await location(params);
    if (response.code === 200 && response.data.length >= 0) {
      areaCodelist.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};
const options = ref([]);

const handelIndustry = async () => {
  const res = await industryApi();
  // console.log(res);
  if (res.code === 200 && res.data) {
    options.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

const handleInput = (type) => {
  // 限制只能输入文字
  val[type] = val[type].replace(/[^\d]/g, "");
};

const handleVal = () => {
  if (val.createInvestment === "" || val.endInvestment === "") {
    // emit("update:value", val.value);
  } else {
    if (Number(val.createInvestment) >= Number(val.endInvestment)) {
      ElMessage({
        type: "warning",
        message: "区间最小值需要小于最大值!",
        onClose: () => {
          val.createInvestment = "";
          val.endInvestment = "";
        },
      });
    }
  }
};

const businessoptions = ref([]);
let optionsList = [
  {
    value: "2",
    label: "计划审批中",
  },
  {
    value: "1",
    label: "计划审批通过",
  },
  {
    value: "0",
    label: "计划审批驳回",
  },
  {
    value: "3",
    label: "计划审批撤回",
  },
];

const column = [
  {
    name: "planName",
    label: "项目名称",
    inSearch: true,
    valueType: "input",
  },
  { name: "planEncode", label: "项目编号", inSearch: true, valueType: "input" },
  {
    name: "planStatus",
    label: "计划状态",
    inSearch: true,
    valueType: "select",
    options: optionsList,
    slot: true,
    minWidth: "140px",
  },
  {
    name: "investment",
    label: "项目总投资额（万元）",
    width: 180,
  },
  {
    name: "createContract",
    label: "工期开始",
  },
  {
    name: "endContract",
    label: "工期结束",
  },

  {
    name: "businessName",
    label: "业务类型",
    inSearch: true,
    valueType: "cascader",
    options: businessoptions,
    propsExpandTrigger: {
      value: "id",
      label: "businessName",
      checkStrictly: true /*  multiple: true, */,
      children: "children",
      emitPath: false,
    },
    // minWidth: "140px",
    width: 200,
  },
  {
    name: "projectCreateTime",
    label: "创建时间",
    // inSearch: true,
    // valueType: "datetime",
  },
  { name: "creator", label: "创建人" },
  { name: "operation", slot: true, fixed: "right", width: 260, label: "操作" },
];

const businessTypeOptions = async () => {
  let params = {};
  const response = await businessTypeList(params);
  if (response.code === 200 && response.data.length) {
    businessoptions.value = response.data;
  } else {
    ElMessage.error(res.msg);
  }
};
const getStatusLabel = (value) => {
  let matchedOption = optionsList.find((option) => option.value === value);
  return matchedOption ? matchedOption.label : "";
};

const list = ref([]);

const businessDictionary = ref([]);

let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);
const createContracts = ref();
const endContracts = ref();

const conversionData = async () => {
  if (datetime.value && datetime.value[0]) {
    createContracts.value = datetime.value[0];
  }
  if (datetime.value && datetime.value[1]) {
    endContracts.value = datetime.value[1];
  }

  if (creatTime.value && creatTime.value[0]) {
    projectCreatesTime.value = creatTime.value[0];
  }

  if (creatTime.value && creatTime.value[1]) {
    projectEndTime.value = creatTime.value[1];
  }

  if (datetime.value === null) {
    createContracts.value = "";
    endContracts.value = "";
  }
  if (creatTime.value === null) {
    projectCreatesTime.value = "";
    projectEndTime.value = "";
  }
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...val,
    enterpriseName: enterpriseName.value,
    industry: industry.value && industry.value.join(),
    createContracts: createContracts.value,
    endContracts: endContracts.value,
    projectCreatesTime: projectCreatesTime.value,
    projectEndTime: projectEndTime.value,
  };
  params["addressList"] = addressList.value && addressList.value.join();

  if (paramsSubmit) {
    for (let key in paramsSubmit) {
      if (paramsSubmit[key]) {
        params[key] = paramsSubmit[key];
      }
    }
  }

  const res = await conversionList(params);

  if (res.code === 200 && res.rows.length >= 0) {
    list.value = res.rows;
    total.value = Number(res.total);
  } else {
    ElMessage.error(res.msg);
    // 进行提示
    loading.value = false;
  }
};

const reset = (value) => {
  value = "";
  addressList.value = [];
  enterpriseName.value = "";
  val.createInvestment = "";
  val.endInvestment = "";
  createContracts.value = "";
  endContracts.value = "";
  datetime.value = "";
  projectCreatesTime.value = "";
  projectEndTime.value = "";
  creatTime.value = "";
  industry.value = "";
  conversionData();
};

let paramsSubmit;

const onSubmit = (val) => {
  if (val) {
    val.projectCreateTime = formatDate(val.projectCreateTime);
    paramsSubmit = val;
    conversionData();
  }
};

const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  conversionData();
};
const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  conversionData();
};

// 导出
function exportExcelAction(val) {
  if (datetime.value && datetime.value[0]) {
    createContract.value = datetime.value[0];
  }
  if (datetime.value && datetime.value[1]) {
    endContracts.value = datetime.value[1];
  }
  if (datetime.value === null) {
    createContracts.value = "";
    endContracts.value = "";
  }

  if (creatTime.value && creatTime.value[0]) {
    projectCreatesTime.value = creatTime.value[0];
  }

  if (creatTime.value && creatTime.value[1]) {
    projectEndTime.value = creatTime.value[1];
  }

  if (creatTime.value === null) {
    createContracts.value = "";
    endContracts.value = "";
  }

  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...val,
    enterpriseName: enterpriseName.value,
    industry: industry.value && industry.value.join(),
    createContracts: createContracts.value,
    endContracts: endContracts.value,
    projectCreatesTime: projectCreatesTime.value,
    projectEndTime: projectEndTime.value,
  };
  params["addressList"] = addressList.value && addressList.value.join();

  if (val) {
    for (let key in val) {
      if (val[key]) {
        params[key] = val[key];
      }
    }
  }

  proxy.download(
    "/system/plan/export",
    params,
    `项目信息_${
      new Date().getFullYear() +
      "-" +
      new Date().getMonth() +
      1 +
      "-" +
      new Date().getDate()
    }.xlsx`
  );
}

// 转立项
const approval = (value) => {
  
  router.push({
    path: "/myProject/approval/edit",
    query: {
      planId: value.planId,
      name: 1,
      creator:value.creator
      // show:'1',
    },
  });
};

// 项目转化
const handleAdd = () => {
  router.push({
    path: "/myProject/conversion-info/info",
    query: {
      name: 1,
    },
  });
};

// 编辑
const handeleEdit = (value) => {
  router.push({
    path: "/myProject/conversion-info/info",
    query: {
      name: 2,
      planId: value.planId,
    },
  });
};

//详情
const handleDetails = (value) => {
  router.push({
    path: "/myProject/conversion-info/info",
    query: {
      name: 3,
      planId: value.planId,
      showDetails: "2",
    },
  });
};

// 删除
const handelDelete = (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row && row.planId) {
        const result = await deleconversion(row.planId);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          conversionData();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      ElMessage.error(result.msg);
      console.log(err);
    });
};

const handeleRevoke = (row) => {
  ElMessageBox.confirm("确定要撤回吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row) {
        const result = await withdrawApi(row);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          conversionData();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      ElMessage.error("取消");
      // console.log('取消');
    });
};

onMounted(async () => {
  await conversionData();
  await businessTypeOptions();
  await handelLocation();
  // 行业
  await handelIndustry();
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>
<style>
/* .search-form{
  display: flex;
} */
.el-dialog {
  background-color: #f0f2f5;
}

.el-dialog__footer {
  text-align: center;
}
.converDialog {
  position: absolute;
  left: 15%;
  top: -30px;
}
.el-dialog__header {
  margin-right: 0 !important;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  /* padding-bottom: 15px !important; */
}
</style>

<style scoped lang="scss">
.container {
  padding: 20px;
}
// .edit-input{
//   display: flex;

// }
//   .edit-input {
//     padding-right: 100px;
//   }
//   .app-container {
//     flex: 1;
//     display: flex;
//     width: 100%;
//     /* padding: 16px; */
//     box-sizing: border-box;
//   }
//   .cancel-btn {
//     position: absolute;
//     right: 15px;
//     top: 10px;
//   }
</style>
